import { useRoute } from 'vue-router'
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { getCookieToken } from '../../../../common/manager/PermissionManager'
import { appState, exitApp } from '../../../../common/manager/appManager'
import { createOID, jsonString } from '../../../../common/utils/normalUtils'
import { changeRouteExecute, routeConst, setDocumentTitle } from '../../../../router'
import { getSystemByEncodeValue } from '../../../../common/utils/OldSysTools'
import { createSysEmbedUrl } from '../../../../common/manager/appEmbedManager'

/**
 * temp??? 这种整个跳转还用iframe嵌入的很不好理解 这里只是把原有逻辑及代码整理搬迁 并 把消息处理逻辑整理封装
  */
export function useOldFrameSysManager() {
    const route = useRoute()
    const state = reactive({
        isLoading: false,
        urlList: [],
        currentIndex: 0,
        framePath: '',
        loaded: false
    })
    // 超时时钟
    let _cid:any = ''
    // 超时时长
    const timeOutDur = 3000
    // 子系统容器
    const iframeRef = ref()
    // 传给子系统的参数 照搬旧系统
    const frameParams:any = {
        token: getCookieToken(),
        userId: appState.currentUser.userId,
        userInfo: appState.oldCatch.userInfo,
        btn: appState.oldCatch.btnInfo,
        fromUrl: location.href.split('#')[0].split('?')[0],
        iconPath: appState.iconPath,
        projTheme: appState.theme,
        menu: [],
        childMenu: []
    }

    /**
     * 加载完成 这块有缺陷 先照搬 需要子系统配合修改 temp???
     */
    const onLoadHandler = () => {
        state.isLoading = false
        if (!iframeRef.value.contentWindow) return
        state.loaded = true
        clearTimeout(_cid)
        console.log(frameParams, '<---------------------------------------------send frame params')
        iframeRef.value.contentWindow.postMessage(jsonString(frameParams), '*')
    }


    /**
     * 消息处理
     */
    const messageHandler = (e:any) => {
        console.log('--------messageHandler----接收到--：', e)
        if (!e.data) return
        const code = String(e.data.code)
        // 退回主页
        if (code === '1') {
            changeRouteExecute(routeConst.HOME_NAV)
            return
        }
        // 退出登录
        if (code === '2') {
            exitApp()
        }
    }

    /**
     * 这块判断都不准 都是依赖超时时间长短来判断的  如果网速慢都超时就完了 temp????
     */
    const loadFrameContent = async () => {
        if (state.currentIndex >= state.urlList.length) {
            state.isLoading = false
            return
        }
        state.isLoading = true
        const url = state.urlList[state.currentIndex]
        state.framePath = url
        state.currentIndex += 1
        _cid = setTimeout(() => {
            clearTimeout(_cid)
            if (!state.loaded)loadFrameContent()
        }, timeOutDur)
    }

    /**
     * 初始化
     */
    onMounted(() => {
        const params = route.params
        // 如果没有参数跳转404
        if (!params || !params.id) {
            changeRouteExecute(routeConst.ERROR_404)
            return
        }
        // 获取菜单对象
        const sysMenu = getSystemByEncodeValue(appState.navMenuList, String(params.id))
        // 新的权限菜单里没有 跳转403
        if (!sysMenu) {
            changeRouteExecute(routeConst.ERROR_403)
            return
        }
        // 添加消息监听
        window.addEventListener('message', messageHandler)
        // 按照原有逻辑凑参数
        frameParams.menu = sysMenu.children || []
        frameParams.childMenu = [sysMenu]
        if (sysMenu.meta && sysMenu.meta.title) setDocumentTitle(sysMenu.meta.title)
        // 地址有多个 一个失败试下一个
        state.urlList = (sysMenu.framePath || '').split(',')
        iframeRef.value.onload = () => { onLoadHandler() }
        // 开始加载
        loadFrameContent()
    })

    onUnmounted(() => {
        if (_cid)clearTimeout(_cid)
        window.removeEventListener('message', messageHandler)
    })

    return { state, iframeRef }
}


/**
 * temp??? 这种整个跳转还用iframe嵌入的很不好理解 这里只是把原有逻辑及代码整理搬迁 并 把消息处理逻辑整理封装
 */
export function useFrameSysManager() {
    const route = useRoute()
    const state = reactive({
        isLoading: false,
        urlList: [],
        currentIndex: 0,
        framePath: '',
        loaded: false,
        uuid: createOID()
    })
    // 超时时钟
    let _cid:any = ''
    // 超时时长
    const timeOutDur = 3000
    // 子系统容器
    const iframeRef = ref()
    // 传给子系统的参数 照搬旧系统
    const frameParams:any = {
        token: getCookieToken(),
        userId: appState.currentUser.userId,
        userInfo: appState.oldCatch.userInfo,
        btn: appState.oldCatch.btnInfo,
        fromUrl: location.href.split('#')[0].split('?')[0],
        iconPath: appState.iconPath,
        projTheme: appState.theme,
        menu: [],
        childMenu: []
    }

    /**
     * 消息处理
     */
    const messageHandler = (e:any) => {
        console.log('--------messageHandler----接收到--：', e)
        if (!e.data) return

        // 初始化事件
        if (e.data.type === 'init' && e.data.uuid === state.uuid) {
            state.isLoading = false
            state.loaded = true
            clearTimeout(_cid)
            console.log(frameParams, '<----------------init-----------------------------send frame params')
            iframeRef.value.contentWindow.postMessage(jsonString(frameParams), '*')
            return
        }
        // 返回首页
        if (e.data.type === 'home' && e.data.uuid === state.uuid) {
            changeRouteExecute(routeConst.HOME_NAV)
            return
        }
        // 退出
        if (e.data.type === 'exit' && e.data.uuid === state.uuid) {
            exitApp()
            return
        }

        // 以前的兼容下---------------------------------------------------------------
        const code = String(e.data.code)
        // 退回主页
        if (code === '1') {
            changeRouteExecute(routeConst.HOME_NAV)
            return
        }
        // 退出登录
        if (code === '2') {
            exitApp()
        }
    }

    /**
     * 这块判断都不准 都是依赖超时时间长短来判断的  如果网速慢都超时就完了 temp????
     */
    const loadFrameContent = async () => {
        if (state.currentIndex >= state.urlList.length) {
            state.isLoading = false
            return
        }
        state.isLoading = true
        const url = state.urlList[state.currentIndex]
        state.framePath = createSysEmbedUrl(url, state.uuid, '1')
        state.currentIndex += 1
        _cid = setTimeout(() => {
            clearTimeout(_cid)
            if (!state.loaded)loadFrameContent()
        }, timeOutDur)
    }

    /**
     * 初始化
     */
    onMounted(() => {
        const params = route.params
        // 如果没有参数跳转404
        if (!params || !params.id) {
            changeRouteExecute(routeConst.ERROR_404)
            return
        }
        // 获取菜单对象
        const sysMenu = getSystemByEncodeValue(appState.navMenuList, String(params.id))
        // 新的权限菜单里没有 跳转403
        if (!sysMenu) {
            changeRouteExecute(routeConst.ERROR_403)
            return
        }
        // 添加消息监听
        window.addEventListener('message', messageHandler)
        // 按照原有逻辑凑参数
        frameParams.menu = sysMenu.children || []
        frameParams.childMenu = [sysMenu]
        if (sysMenu.meta && sysMenu.meta.title) setDocumentTitle(sysMenu.meta.title)
        // 地址有多个 一个失败试下一个
        state.urlList = (sysMenu.framePath || '').split(',')
        // 开始加载
        loadFrameContent()
    })

    onUnmounted(() => {
        if (_cid)clearTimeout(_cid)
        window.removeEventListener('message', messageHandler)
    })

    return { state, iframeRef }
}
